<template>
  <div class="news-list">
    <div class="news-item" v-for="news in newsList" :key="news.id">
      <div class="news-image">
        <img :src="news.image" :alt="news.title">
      </div>
      <div class="news-content">
        <h3 class="news-title">
          <router-link :to="`/news/article/${news.id}`">{{ news.title }}</router-link>
        </h3>
        <p class="news-summary">{{ news.summary }}</p>
        <div class="news-meta">
          <span class="news-date">{{ formatDate(news.date) }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { fetchNewsList, NewsItem } from '@/apis/news'

// 注释掉模拟数据
// const newsList = ref([
//   { ... },
//   ...
// ])

const newsList = ref<NewsItem[]>([])

onMounted(async () => {
  try {
    const data = await fetchNewsList();
    console.log('获取到的新闻数据：', data); // 检查是否有数据
    newsList.value = data;
  } catch (err) {
    console.error('请求失败：', err); // 查看错误原因
  }
});

function formatDate(dateStr: string) {
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}
</script>

<style lang="scss" scoped>
.news-list {
  .news-item {
    display: flex;
    padding: 20px 0;
    border-bottom: 1px solid #eee;
    &:last-child { border-bottom: none; }
    @media (max-width: 576px) { flex-direction: column; }
  }
  .news-image {
    width: 200px;
    height: 130px;
    border-radius: 4px;
    overflow: hidden;
    margin-right: 20px;
    flex-shrink: 0;
    @media (max-width: 576px) { width: 100%; height: auto; margin-right: 0; margin-bottom: 15px; }
    img { width: 100%; height: 100%; object-fit: cover; transition: transform 0.3s; &:hover { transform: scale(1.05); } }
  }
  .news-content {
    flex: 1;
    position: relative;
    padding-bottom: 30px;
  }
  .news-title {
    font-size: 18px;
    font-weight: bold;
    margin: 0 0 10px;
    a { color: #333; text-decoration: none; transition: color 0.3s; &:hover { color: #ff6b9d; } }
  }
  .news-summary {
    font-size: 14px;
    color: #666;
    margin: 0;
    line-height: 1.6;
  }
  .news-meta {
    position: absolute;
    bottom: 0;
    right: 0;
    font-size: 12px;
    color: #999;
  }
}
</style>